<?php

namespace app\api\controller;

use app\common\controller\Api;
use EasyWeChat\Kernel\Messages\Location;
use fast\Http;
use think\Request;

/**
 * 首页接口
 */
class Oauth extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     *
     */
    public function index()
    {
        $params = $this->request->param();

        if (!isset($params['code'])) {
            $this->error('授权失败');
        }

        //微信授权openid
        $code = $params['code'];
        parse_str($params['state'], $stateArray);

        $params = Db('orderPost')->where(['id' => $stateArray['orderpostid']])->find();
        $codeListsInfo = Db('payCodeLists')->where(['appid' => $params['appid']])->find();

        $openid = $this->getOpenId($code,$codeListsInfo['appid'],$codeListsInfo['appsecret']);

        Db('orderPost')->where(['id' => $stateArray['orderpostid']])->update(['openid' => $openid]);

        $domain = Request::instance()->domain();

        $orderPost = Db('orderPost')->where(['id' => $stateArray['orderpostid']])->find();

        $redirectUri = ($domain . '/index.html#/?orderpostid='.$stateArray['orderpostid'].'&price='.$orderPost['price'].'&ip='.$orderPost['ip']);

        header("location: ".$redirectUri);
    }

    function getOpenId($code,$appid,$appsecret)
    {

        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$appsecret}&code={$code}&grant_type=authorization_code";

        // 发送 HTTP 请求
        $response = file_get_contents($url);
        $data = json_decode($response, true);

        // 检查返回结果
        if (isset($data['openid'])) {
            return $data['openid']; // 返回 openid
        } else {
            // 返回错误信息
            return $data['errmsg'] ?? '获取 openid 失败';
        }
    }


}
